package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venueservice.dao.ServiceProviderUserMapper;
import com.eastfair.venueservice.dto.ServiceProviderUserDTO;
import com.eastfair.venueservice.entity.ServiceProvider;
import com.eastfair.venueservice.entity.ServiceProviderUser;
import com.eastfair.venueservice.service.ServiceProviderUserService;
import com.eastfair.venueservice.vo.ServiceProviderUserVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 服务商用户关系
 * </p>
 *
 * @author dqq
 * @date 2023-02-02
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ServiceProviderUserServiceImpl extends SuperServiceImpl<ServiceProviderUserMapper, ServiceProviderUser> implements ServiceProviderUserService {

    @Override
    protected R<Boolean> handlerSave(ServiceProviderUser model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public List<ServiceProviderUser> listServiceProviderUser(ServiceProviderUserDTO serviceProviderUserDTO) {
        QueryWrapper<ServiceProviderUser> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ServiceProviderUser::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(serviceProviderUserDTO.getServiceProviderId() != null,
                        ServiceProviderUser::getServiceProviderId, serviceProviderUserDTO.getServiceProviderId())
                .eq(StrUtil.isNotBlank(serviceProviderUserDTO.getServiceProviderType()),
                        ServiceProviderUser::getServiceProviderType, serviceProviderUserDTO.getServiceProviderType())
                .eq(serviceProviderUserDTO.getUserId() != null,
                        ServiceProviderUser::getUserId, serviceProviderUserDTO.getUserId())
                .in(serviceProviderUserDTO.getUserIdList() != null && !serviceProviderUserDTO.getUserIdList().isEmpty(),
                        ServiceProviderUser::getUserId, serviceProviderUserDTO.getUserIdList())
                .eq(serviceProviderUserDTO.getIsMainAccount() != null,
                        ServiceProviderUser::getIsMainAccount, serviceProviderUserDTO.getIsMainAccount())
                .eq(serviceProviderUserDTO.getIsUserFirstRegister() != null,
                        ServiceProviderUser::getIsUserFirstRegister, serviceProviderUserDTO.getIsUserFirstRegister())
        ;
        return list(queryWrapper);
    }

    @Override
    public List<ServiceProviderUserVO> listVOByIds(List<Long> userIdList, Long serviceProviderId, String serviceProviderType) {
        log.info("listVOByIds - 用户ID批量获取服务商用户关系, userId={}, serviceProviderId={}, serviceProviderType={}",
                userIdList, serviceProviderId, serviceProviderType);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setServiceProviderId(serviceProviderId);
        query.setServiceProviderType(serviceProviderType);
        query.setUserIdList(userIdList);
        List<ServiceProviderUser> list = listServiceProviderUser(query);
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return list
                .stream()
                .map(serviceProviderUser -> BeanUtil.toBean(serviceProviderUser, ServiceProviderUserVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public ServiceProviderUser getMainAccountUser(Long serviceProviderId, String serviceProviderType) {
        log.info("getMainAccountUser - 获取服务商的主用户, serviceProviderId={}, serviceProviderType={}", serviceProviderId, serviceProviderType);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setServiceProviderId(serviceProviderId);
        query.setServiceProviderType(serviceProviderType);
        query.setIsMainAccount(BusinessConstant.YES);
        List<ServiceProviderUser> serviceProviderUsers = listServiceProviderUser(query);
        if (serviceProviderUsers == null || serviceProviderUsers.isEmpty()) {
            return null;
        }
        return serviceProviderUsers.get(0);
    }

    @Override
    public ServiceProviderUser getByUserId(Long userId, String serviceProviderType) {
        log.info("getByUserId - 用户ID, 服务商类型查询绑定的服务商, userId={}, serviceProviderType={}", userId, serviceProviderType);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setUserId(userId);
        query.setServiceProviderType(serviceProviderType);
        List<ServiceProviderUser> serviceProviderUsers = listServiceProviderUser(query);
        if (serviceProviderUsers == null || serviceProviderUsers.isEmpty()) {
            return null;
        }
        return serviceProviderUsers.get(0);
    }

    @Override
    public ServiceProviderUser getFirstRegisterMainByUserId(Long userId) {
        log.info("getFirstRegisterMainByUserId - 获取主用户注册的第一个服务商关系, userId={}", userId);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setUserId(userId);
        query.setIsMainAccount(BusinessConstant.YES);
        query.setIsUserFirstRegister(BusinessConstant.YES);
        List<ServiceProviderUser> list = listServiceProviderUser(query);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public boolean existServiceProviderUser(Long userId, Long serviceProviderId, String serviceProviderType) {
        // 校验服务商用户关系是否已存在
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setUserId(userId);
        query.setServiceProviderType(serviceProviderType);
        List<ServiceProviderUser> existList = listServiceProviderUser(query);
        if (existList != null && !existList.isEmpty()) {
            ServiceProviderUser serviceProviderUser = existList.get(0);
            if (!serviceProviderUser.getServiceProviderId().equals(serviceProviderId)) {
                throw BizException.wrap(-1, "该用户已与其他服务商绑定，不可再绑定");
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveServiceProviderUser(ServiceProviderUserDTO param) {
        log.info("saveServiceProviderUser - 保存服务商，用户关系, serviceProviderUserDTO={}", param);
        // 校验服务商用户关系是否已存在
        boolean existServiceProviderUser = existServiceProviderUser(param.getUserId(), param.getServiceProviderId(), param.getServiceProviderType());
        if (existServiceProviderUser) {
            return true;
        }
        // 是否是主用户
        if (param.getIsMainAccount() == null) {
            param.setIsMainAccount(BusinessConstant.NO);
            param.setIsUserFirstRegister(BusinessConstant.NO);
        }
        // 是否是作为主用户注册的第一个服务商
        if (param.getIsMainAccount() == BusinessConstant.YES) {
            ServiceProviderUser firstServiceProviderUser = getFirstRegisterMainByUserId(param.getUserId());
            if (firstServiceProviderUser == null) {
                param.setIsUserFirstRegister(BusinessConstant.YES);
            } else {
                param.setIsUserFirstRegister(BusinessConstant.NO);
            }
        }
        ServiceProviderUser serviceProviderUser = BeanUtil.toBean(param, ServiceProviderUser.class);
        return save(serviceProviderUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByServiceProviderId(Long serviceProviderId) {
        log.info("removeByServiceProviderId - 服务商ID移除服务商关系, serviceProviderId={}", serviceProviderId);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setServiceProviderId(serviceProviderId);
        List<ServiceProviderUser> list = listServiceProviderUser(query);
        if (list == null || list.isEmpty()) {
            return false;
        }
        List<Long> ids = list
                .stream()
                .map(SuperEntity::getId)
                .collect(Collectors.toList());
        return removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByUserId(Long userId) {
        log.info("removeByUserId - 用户ID移除服务商关系, userId={}", userId);
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setUserId(userId);
        List<ServiceProviderUser> list = listServiceProviderUser(query);
        if (list == null || list.isEmpty()) {
            return false;
        }
        List<Long> ids = list
                .stream()
                .map(SuperEntity::getId)
                .collect(Collectors.toList());
        return removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeServiceProviderUser(Long userId, Long serviceProviderId, String serviceProviderType) {
        ServiceProviderUserDTO query = new ServiceProviderUserDTO();
        query.setUserId(userId);
        query.setServiceProviderId(serviceProviderId);
        query.setServiceProviderType(serviceProviderType);
        List<ServiceProviderUser> list = listServiceProviderUser(query);
        if (list == null || list.isEmpty()) {
            return false;
        }
        List<Long> ids = list
                .stream()
                .map(SuperEntity::getId)
                .collect(Collectors.toList());
        return removeByIds(ids);
    }

    @Override
    public boolean removeServiceProviderUser(List<Long> userIdList, Long serviceProviderId, String serviceProviderType) {
        log.info("removeServiceProviderUser - 批量移除用户，服务商关系, userIdList={}, serviceProviderId={}, serviceProviderType={}",
                userIdList, serviceProviderId, serviceProviderType);
        if (userIdList == null || userIdList.isEmpty()) {
            return false;
        }
        for (Long userId : userIdList) {
            removeServiceProviderUser(userId, serviceProviderId, serviceProviderType);
        }
        return true;
    }


    @Override
    public List<ServiceProviderUserVO> listWaitCmsUserSync() {
        log.info("listWaitCmsUserSync - 查询待同步cms的服务商用户");
        QueryWrapper<ServiceProviderUser> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ServiceProviderUser::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(ServiceProviderUser::getCmsSync, BusinessConstant.NO)
                .orderByAsc(ServiceProviderUser::getUpdateTime)
                .last("limit 100")
        ;
        List<ServiceProviderUser> list = list(queryWrapper);
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        List<ServiceProviderUserVO> serviceProviderUserVOS = list.stream().map(serviceProviderUser -> BeanUtil.toBean(serviceProviderUser, ServiceProviderUserVO.class)).collect(Collectors.toList());

        //组装公司社会编码
        return serviceProviderUserVOS;
    }


}
